package com.mengze.linlee_iot_adnroid.activity

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.core.app.ActivityCompat
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.mengze.linlee_iot_adnroid.R
import com.mengze.linlee_iot_adnroid.adapter.DeviceAdapter
import com.mengze.linlee_iot_adnroid.databinding.ActivityBlueDeviceListBinding
import com.mengze.linlee_iot_adnroid.databinding.ActivityWifiConnectionBinding

class BlueDeviceListActivity : AppCompatActivity() {

    private  lateinit var binding: ActivityBlueDeviceListBinding
    private lateinit var recyclerView: RecyclerView
    private lateinit var bluetoothAdapter: BluetoothAdapter
    private val deviceList = mutableListOf<String>(
        "蓝牙1",
        "蓝牙2",
        "蓝牙3",
        "蓝牙4",
        "蓝牙2",
        "蓝牙3",
        "蓝牙1",
        "蓝牙2",
        "蓝牙3",
        "蓝牙4",
        "蓝牙2",
        "蓝牙3",
        "蓝牙1",
        "蓝牙2",
        "蓝牙3",
        "蓝牙4",
        "蓝牙2",
        "蓝牙3",
        "蓝牙1",
        "蓝牙2",
        "蓝牙3",
        "蓝牙4",
        "蓝牙2",
        "蓝牙3"
    )
    private val scanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {

            print("ScanResult: ")
            print(result)
            result.device?.name?.let {
                if(!deviceList.contains(it)) {

                    print("deviceList:" )
                    print(deviceList)
                    deviceList.add(it)
//                    recyclerView.adapter?.notifyItemInserted(deviceList.size - 1)
                }
            }
        }
    }

    private fun updateStatusBarAndNavBar(){
        binding = ActivityBlueDeviceListBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.toolbarTitle.text = "可用蓝牙列表"
        window.statusBarColor = Color.parseColor("#FF54D437") // 橙色
        window.apply {
            var statusBarColor = Color.parseColor("#FF54D437") // 设置颜色
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        updateStatusBarAndNavBar();


        binding?.recyclerView?.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = DeviceAdapter(deviceList){ item ->
            when (item) {

            }
        }

        val bluetoothManager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter



        println("222222 onCreate~~~")
        checkPermissions()
        println("onCreate~~~")
    }


//    // todo 蓝牙动态申请权限
//    private fun initPermission() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
//            // Android 版本大于等于 Android12 时
//            // 只包括蓝牙这部分的权限，其余的需要什么权限自己添加
//            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN)
//            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE)
//            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT)
//        } else {
//            // Android 版本小于 Android12 及以下版本
//            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION)
//            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)
//        }
//        if (mPermissionList.size() > 0) {
//            ActivityCompat.requestPermissions(
//                getActivity(),
//                mPermissionList.toArray(arrayOfNulls<String>(0)),
//                1001
//            )
//        }
//    }


    private fun checkPermissions() {


        //动态申请
        val LOCATION_PERMISSION =
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
                arrayOf(
                    //注册精准位置权限，否则可能Ble扫描不到设备
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                )
            } else {
                arrayOf(
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_CONNECT,
                )
            }

        println("checkPermissions~1111~~")
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            println("checkSelfPermission~~~~")
                    ActivityCompat.requestPermissions(this,
                        LOCATION_PERMISSION, 1)

        } else {

            println("startScan~~~~")
            startScan()
        }
    }

    private fun startScan() {
        val scanner = bluetoothAdapter.bluetoothLeScanner
        if (!bluetoothAdapter.isEnabled) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBtIntent, 1002)
        }

        scanner.startScan(scanCallback)
//        Handler(Looper.getMainLooper()).postDelayed({
//            scanner.stopScan(scanCallback)
//        }, 10000)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1 && grantResults.isNotEmpty() &&
            grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startScan()
        }
    }

}